﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SiGeSIB.GUI.Common;
using SiGeSIB.Services;
using System.IO;

namespace SiGeSIB.GUI.BackupRestoration
{
	public partial class FBackup : Form
	{
		public enum EBackupFunctionality
		{
			Backup,
			Restoration
		}

		public FBackup(EBackupFunctionality func)
		{
			InitializeComponent();
			this.StartPosition = FormStartPosition.CenterParent;

			_Functionality = func;

			switch (func)
			{
				case EBackupFunctionality.Backup:
					if (saveDialog.ShowDialog() == DialogResult.OK)
					{
						_FileName = saveDialog.FileName;
						this.ShowDialog();
					}
					else
						this.Close();
					break;
				case EBackupFunctionality.Restoration:
					if (openDialog.ShowDialog() == DialogResult.OK)
					{
						_FileName = openDialog.FileName;
						this.ShowDialog();
					}
					else
						this.Close();
					break;
				default:
					break;
			}
		}

		private EBackupFunctionality _Functionality;
		private string _FileName;

		private const string BACKUP_WAITING_MESSAGE = "Aguare, realizando backup do sistema.";
		private const string BACKUP_MESSAGE = "Backup realizado com sucesso!";
		private const string RESTORATION_BACKUP_WAITING_MESSAGE = "Aguare, realizando recuperação do backup do sistema.";
		private const string RESTORATION_BACKUP_MESSAGE = "Recuperação do backup realizada com sucesso!";

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			label1.Text = _Functionality == EBackupFunctionality.Backup ? BACKUP_WAITING_MESSAGE : RESTORATION_BACKUP_WAITING_MESSAGE;
			btnClose.Enabled = false;
			
			bwBackup.RunWorkerAsync();
		}

		private void bwBackup_DoWork(object sender, DoWorkEventArgs e)
		{
			IBackupRestorationServicesProvider secProv = Manager.Instance.ServicesProvider.CreateBackupRestorationServicesProvider();

			if (_Functionality == EBackupFunctionality.Backup)
				secProv.Backup(_FileName);
			else
				secProv.RestoreBackup(_FileName);
		}

		private void bwBackup_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			if (!IsDisposed)
			{
				if (e.Error == null)
				{
					btnClose.Enabled = true;
					progressBar1.Style = ProgressBarStyle.Continuous;
					progressBar1.Value = 100;

					label1.Text = _Functionality == EBackupFunctionality.Backup ? BACKUP_MESSAGE : RESTORATION_BACKUP_MESSAGE;
				}
				else
				{
					btnClose.Enabled = true;
					progressBar1.Style = ProgressBarStyle.Continuous;
					label1.Text = e.Error.Message;
					label1.ForeColor = Color.Red;
				}
			}
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}
